package com.tang.netty.nio.server;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * 服务端
 */
@Slf4j
public class NioServer {

    private Selector selector;
    private ServerSocketChannel socketChannel;
    
    public static void main(String[] args) {
        new NioServer().bind(7397);
    }

    public void bind(int port) {
        try {
            // 1.创建Selector
            selector = Selector.open();
            // 2.通过ServerSocketChannel创建Channel通道
            socketChannel = ServerSocketChannel.open();
            // 3.为Channel通道绑定监听端口
            socketChannel.bind(new InetSocketAddress(port));
            // 4.设置Channel为非阻塞模式
            socketChannel.configureBlocking(false);
            // 5.将Channel注册到Selector上，监听连接事件
            socketChannel.register(selector, SelectionKey.OP_ACCEPT);
            log.info("nio server start done!");
            // 6.开启线程
            new NioServerHandler(selector, StandardCharsets.UTF_8).start();
            log.info("========bind结束========");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
